<template>
  <div class="ads-container"
       v-loading="loading">
    <div class="ads-account-box">
      <span class='ads-container-left'>导出账户</span>
      <el-select v-model="value"
                 multiple
                 filterable
                 default-first-option
                 placeholder="请选择广告账户"
                 class="ads-select-container">
        <el-option v-for="item in options"
                   :key="item.id"
                   :label="item.name + '-' +item.id"
                   :value="item.id">
        </el-option>
      </el-select>
      <el-button class="select-all"
                 type="primary"
                 @click="selectAll">{{all_cancel}} {{options.length > 1 ? `(${options.length})` : ``}}</el-button>
    </div>
    <div class="ads-account-box">
      <span class="ads-container-left">导出范围</span>
      <el-date-picker v-model="date"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
      </el-date-picker>
    </div>
    <div class="ads-radio-container">
      <el-radio-group v-model="radio">
        <el-radio :label="0">{{daily.name}}</el-radio>
        <el-radio :label="1">{{basic.name}}</el-radio>
        <el-radio :label="2">{{subdivision.name}}</el-radio>
      </el-radio-group>
    </div>
    <el-button type="primary"
               @click="selectExcel">先获取数据<i class="el-icon-download el-icon--right"></i></el-button>
    <el-button type="primary"
               @click="exportData">等加载完后导出<i class="el-icon-share el-icon--right"></i></el-button>
  </div>
</template>

<script>
import { getInsights, getMoreInsights, getVideo, getAdimages } from 'utils/api'
import { addDate, getDayGroup } from 'utils/utils'
import {
  daily, basic, subdivision, video_keys
} from 'utils/config'
import Nprogress from 'nprogress'
import { mapGetters } from 'vuex'
export default {

  data () {
    return {
      // 广告账户
      value: [],
      // 时间范围
      date: '',
      // 报表的选择. 0 1 2: 日常,基本,细分
      radio: 0,
      excelData: {
        data: []
      },
      daily, basic, subdivision,
      timer: null
    }
  },
  methods: {

    clearExcelData () {
      if (this.excelData.data.length) {
        this.excelData.data = []
        delete this.excelData.someData
      }
    },
    // 合并成一张表导出
    exportData () {
      console.log(this.excelData.data)
      if (this.excelData.data.length) {
        let someData = this.excelData.someData
        this.export2Excel(someData.head, someData.head_key, this.excelData.data, `${addDate(this.date[0])}~${addDate(this.date[1])}`)
      } else {
        this.$message.error('目前数据为空,请重新获取数据后导出!')
      }
    },
    startNprogress (time = 13000) {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        Nprogress.done()
      }, time)
    },
    // 数据值转数字
    text2number (arr, res) {
      return res.map((item) => {
        arr.forEach((key) => {
          item[key] = item[key] * 1
        })
        return item
      })
    },
    // 获取顾问跟踪表
    async getSubdivisionData (start_time, end_time) {
      // let res = this.handleActions(this.subdivisionAddData(await getMoreInsights(`act_309850329720524/campaigns`, subdivision.param("2019-09-16", "2019-09-16")),{ name: "", id: "" }))
      // console.log(res)
      this.getExcelData(start_time, end_time, subdivision.head, subdivision.head_key, subdivision.name, subdivision.number_key, async (start, end, id, account) => {
        return this.handleActions(this.subdivisionAddData(await getMoreInsights(`${id}/campaigns`, subdivision.param(start, end)), account), true)
      })
    },
    // 处理顾问跟踪表的数据
    subdivisionAddData (arr, account) {
      return arr.map(item => {
        let insights = {}
        if (item.insights) {
          insights = this.handSomeCost(item.insights.data[0])
        } else {
          insights = { account_id: account.id.replace('act_', ''), account_name: account.name, campaign_name: item.name }
        }
        return {
          daily_budget: (item.daily_budget / 100) || '使用广告组预算',
          ...insights
        }
      })
    },
    // 处理一些费用
    handSomeCost (res) {
      res.inline_link_clicks_spend = res.inline_link_clicks * 1 && (res.spend / res.inline_link_clicks).toFixed(2) || '-'
      res.inline_link_clicks_impressions = res.inline_link_clicks * 1 && (res.impressions / res.inline_link_clicks).toFixed(2) || '-'
      res.clicks_impressions = res.clicks * 1 && (res.impressions / res.clicks).toFixed(2) || '-'
      res.clicks_spend = res.clicks * 1 && (res.spend / res.clicks).toFixed(2) || '-'
      return res
    },

    // 获取素材基本数据表
    getBasicData (start_time, end_time) {
      this.getExcelData(start_time, end_time, basic.head, basic.head_key, basic.name, basic.number_key, async (start, end, id, account) => {
        return this.handleActions(this.basicAddData(await getMoreInsights(`${id}/ads`, basic.param(start, end), '', false)))
      })
    },
    // 
    // 处理素材基本数据表的数据
    basicAddData (arr) {
      console.log(arr)
      return arr.map(item => {
        let insights = {}
        insights = this.getVideoValue(item.insights.data[0])
        return {
          created_time: item.created_time,
          material_name: item.material_name || '',
          ...insights
        }
      })
    },
    // 摘出视频相关数据
    getVideoValue (res) {
      var that = this
      video_keys.forEach(item => {
        res = that.handleVideoData(res, item)
      });
      return res
    },
    handleVideoData (res, key) {
      res[key] = res[key] && res[key][0].value || ''

      return res
    },
    // 选择哪张表获取数据
    selectExcel () {
      // console.log(this.date)
      // 请求时先清除
      this.clearExcelData()
      Nprogress.start()
      console.log(this.date)
      // 前提选项
      if (this.date && this.date.length === 2 && this.value.length) {
        this.startNprogress(15000)
        // 时间
        let arr = getDayGroup(this.date[0], this.date[1])
        arr.forEach(day => {
          console.log(day);
          this.radio === daily.excel_label ? this.getDailyData(day, day) : this.radio === basic.excel_label ? this.getBasicData(day, day) : this.getSubdivisionData(day, day)
        });
      } else {
        this.$message.error('请补全导出时间范围和账户, 即日期!')
      }
    },
    // 获取日常表数据并导出
    getDailyData (start_time, end_time) {
      this.getExcelData(start_time, end_time, daily.head, daily.head_key, daily.name, daily.number_key, async (start, end, id, account) => {
        return this.handleActions(await getInsights(id, daily.param, start, end))
      })
    },
    /**
     * 抽离相同模块
     * start_time, end_time, head表头, 
     * head_key表头对应数据的键值, 
     * excel_name表名
     * number_key要转数字的key数组
     * cb数据处理回调
     * */
    getExcelData (start_time, end_time, head, head_key, excel_name, number_key, cb) {
      this.value.map(async (item) => {

        let account = this.options.find(o => o.id === item)
        // 处理回调
        let res = await cb(start_time, end_time, item, account)
        // 数值转数字
        res = this.text2number(number_key, res)
        // 合并表
        this.excelData.data = this.excelData.data.length ? [...this.excelData.data, ...res] : res
        if (!this.excelData.someData) this.excelData.someData = { head, head_key, excel_name }
        console.log(res)
        if (!res.length) {
          this.$notify({
            title: '通知',
            message: `${account.name} ${start_time}中没有数据`,
            position: 'bottom-right'
          });
        }
        // 塞入表名导出
        // res ? this.export2Excel(head, head_key, res, `${account.name}-${start_time}-${excel_name}`) : this.$message.error(`${account.name} ${start_time}中没有数据`)
        // Nprogress.done()
      })
    },
    // 处理日常表数据 actions 把成效抽出来.
    handleActions (res, flag) {
      if (!res.length) return []
      return res.map((item) => {
        let results = item.actions && item.actions.find((action) => {
          // 需求只记录移动应用安装的成效.
          return action.action_type === 'mobile_app_install'
        }) || ''
        item.action_type = results ? results.action_type : ''
        item.action_value = results ? results.value : ''
        // 如果顾问跟踪表
        if (flag) {
          item.action_value_spend = item.action_value && (item.spend / item.action_value).toFixed(2) || ''
          item = this.getCartAndPurchase(item)
        }
        // 删除不要的字段.
        if (item.actions) delete item.actions
        return item
      })
    },

    // 摘出顾问跟踪表数据表中的action应用事件
    getCartAndPurchase (item) {
      let cart = item.actions && item.actions.find(i => i.action_type === 'app_custom_event.fb_mobile_add_to_cart') || ''
      let purchase = item.actions && item.actions.find(i => i.action_type === 'app_custom_event.fb_mobile_purchase') || ''
      let cart_value = item.action_values && item.action_values.find(i => i.action_type === 'app_custom_event.fb_mobile_add_to_cart') || ''
      let purchase_value = item.action_values && item.action_values.find(i => i.action_type === 'app_custom_event.fb_mobile_purchase') || ''
      item.fb_mobile_add_to_cart = cart.value || ''
      item.fb_mobile_add_to_cart_value = cart_value.value || ''
      item.fb_mobile_add_to_cart_spend = cart.value * 1 && (item.spend / cart.value).toFixed(2) || '-'
      item.fb_mobile_purchase = purchase.value || ''
      item.fb_mobile_purchase_value = purchase_value.value || ''
      item.fb_mobile_purchase_spend = purchase.value * 1 && (item.spend / purchase.value).toFixed(2) || '-'
      return item
    },
    /**
     * 表头: tHeader, 数据键值组: filterVal, 数据: list, 表名: name
     */
    export2Excel (tHeader, filterVal, list, name = '无标题报告') {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../utils/Export2Excel');
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, name);  //导出Excel 文件名
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // 可能没有那数据 即没字段
        return v[j] || ''
      }))
    },
    // 全选
    selectAll () {
      if (this.value.length === this.options.length) {
        this.value = []
        return false
      }
      this.value = this.options.map(item => item.id)
    }
  },
  computed: {
    all_cancel () {
      return this.value.length === this.options.length ? '取消' : '全选'
    },
    ...mapGetters(['loading', 'options'])
  },
  watch: {
    'excelData.data.length' (val, old) {
      console.log(val)
      this.startNprogress()
    },
    'value.length' (val) {
      this.clearExcelData()
    },
    radio (val) {
      // 切换 清除
      this.clearExcelData()
    }
  }
}
</script>

<style lang='stylus'  rel='stylesheet/stylus'>
.ads-container
  .ads-container-left
    margin-right 20px
  .ads-select-container
    width 500px
    .el-select__tags
      max-height 250px
      overflow-y scroll
      -ms-overflow-style none
      overflow -moz-scrollbars-none
      &::-webkit-scrollbar
        width 0 !important
  .ads-account-box
    display flex
    margin-bottom 30px
    .ads-container-left
      flex-basis 200px
  .ads-radio-container
    margin-bottom 30px
  .select-all
    margin-left 15px
    max-height 50px
</style>